var util = require('../../utils/util.js');
var api = require('../../config/api.js');

Page({
  data: {
    navList: [],
    categoryList: [],
    currentCategory: {},
    scrollLeft: 0,
    scrollTop: 0,
    goodsCount: 0,
    scrollHeight: 0,
    showModal:false, // 显示modal弹窗
    goodSpecificationList:[],
    goods:{},
    productList: {},

  },
  onLoad: function (options) {
    this.getCatalog();
  },
  getCatalog: function () {
    //CatalogList
    let that = this;
    wx.showLoading({
      title: '加载中...',
    });
    
    util.request(api.CatalogList).then(function (res) {
      // 原有一级菜单
        // that.setData({
        //   navList: res.data.categoryList,
        //   currentCategory: res.data.currentCategory
        // });
        //现改为二级菜单-商品
        that.setData({
            navList: res.data.currentCategory.subCategoryList
          });
          that.getGoodsInfo(res.data.currentCategory.subCategoryList[0].id)

        wx.hideLoading();
      });

    util.request(api.GoodsCount).then(function (res) {
      that.setData({
        goodsCount: res.data.goodsCount
      });
    });

  },
  getCurrentCategory: function (id) {
    let that = this;
    util.request(api.CatalogCurrent, { id: id })
      .then(function (res) {
        that.setData({
          currentCategory: res.data.currentCategory
        });
      });
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  getList: function () {
    var that = this;
    util.request(api.ApiRootUrl + 'api/catalog/' + that.data.currentCategory.cat_id)
      .then(function (res) {
        that.setData({
          categoryList: res.data,
        });
      });
  },
  switchCate: function (event) {
    var that = this;
    var currentTarget = event.currentTarget;
    if (this.data.currentCategory.id == event.currentTarget.dataset.id) {
      return false;
    }

    //原有获取二级菜单
    // this.getCurrentCategory(event.currentTarget.dataset.id);
    //现改为获取具体商品信息
    that.getGoodsInfo(event.currentTarget.dataset.id);
  },
  //获取具体商品信息
  getGoodsInfo:function (id){
    let that = this;
    util.request(api.GoodsList, {categoryId: id, page: 0, size: 100})
      .then(function (res) {
        let currentCategory = res.data.currentCategory;
        currentCategory.subCategoryList = res.data.goodsList;
        that.setData({
          currentCategory: currentCategory,  
        });
      });
  },
  //点击选规格
  clickGood:function(e){
    let that = this;
    util.request(api.GoodsDetail, { id: e.currentTarget.dataset.id }).then(function (res) {
      console.log(res.data)
      that.setData({
        showModal:true,
        goodSpecificationList:res.data.specificationList,
        productList: res.data.productList,
        goods:res.data.info,
      })

      //调用套餐接口
      util.request(api.questionnaireComboInfo, { id: e.currentTarget.dataset.goodsn }).then(function (res) {
        let val1={};
        console.log(res.data[0])
        that.setData({
          
        });
      })
    })
    
  },
  // 选中类型，修改样式
  selectGoodsType:function(e){
    let that = this;
    let checkedid = e.currentTarget.dataset.id;
    let listid = e.currentTarget.dataset.index;
    that.data.goodSpecificationList[listid].valueList.forEach(function(item,index){
      //设置单选
      item.checked = undefined
      if(checkedid == item.id){
          item.checked = true
      }
      //赋值
      let selected = "goodSpecificationList["+listid+"].valueList["+index+"]";
      that.setData({
        [selected]:item
    });
    })
  },
/**
   * 添加到购物车
   */
  addToCart: function () {
    var that = this;
      //提示选择完整规格
      if (!this.isCheckedAllSpec()) {
          wx.showToast({
              title: '请选择完整规格'
          });
        return false;
      }

      //根据选中的规格，判断是否有对应的sku信息
      let checkedProduct = this.getCheckedProductItem(this.getCheckedSpecKey());
      if (!checkedProduct || checkedProduct.length <= 0) {
        //找不到对应的product信息，提示没有库存
        wx.showToast({
          title: '找不到对应的产品信息'
      });
        return false;
      }

      //验证库存
      if (checkedProduct.goods_number < this.data.number) {
        //找不到对应的product信息，提示没有库存
        wx.showToast({
          title: '提示没有库存'
      });
        return false;
      }

      //添加到购物车，暂时添加一个
      util.request(api.CartAdd, { goodsId: this.data.goods.id, number: 1, productId: checkedProduct[0].id }, 'POST', 'application/json')
        .then(function (res) {
          let _res = res;
          if (_res.errno == 0) {
            wx.showToast({
              title: '添加成功'
            });
            that.setData({
              showModal:false
            })
          } else {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: _res.errmsg,
              mask: true
            });
          }

        });
 
  },
  //判断规格是否选择完整
  isCheckedAllSpec: function () {
    return !this.getCheckedSpecValue().some(function (v) {
      if (v.valueId == 0) {
        return true;
      }
    });
  },
  getCheckedProductItem: function (key) {
    return this.data.productList.filter(function (v) {
      if (v.goods_specification_ids.indexOf(key) > -1) {
        return true;
      } else {
        return false;
      }
    });
  },
  getCheckedSpecKey: function () {
    let checkedValue = this.getCheckedSpecValue().map(function (v) {
      return v.valueId;
    });
    // return checkedValue.join(',');
    return checkedValue.join('_');
  },
  //获取选中的规格信息
  getCheckedSpecValue: function () {
    let checkedValues = [];
    let _specificationList = this.data.goodSpecificationList;
    for (let i = 0; i < _specificationList.length; i++) {
      let _checkedObj = {
        nameId: _specificationList[i].specification_id,
        valueId: 0,
        valueText: ''
      };
      for (let j = 0; j < _specificationList[i].valueList.length; j++) {
        if (_specificationList[i].valueList[j].checked) {
          _checkedObj.valueId = _specificationList[i].valueList[j].id;
          _checkedObj.valueText = _specificationList[i].valueList[j].value;
        }
      }
      checkedValues.push(_checkedObj);
    }

    return checkedValues;

  },
})
